package com.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Solution {
    public static void main(String[] args) throws InterruptedException {
        Task task = new Task(100);
//        Thread t1 = new Thread(() -> {
//            try {
//                task.print1();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//
//        }, "--1");
//        Thread t2 = new Thread(() -> {
//            try {
//                task.print2();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }, "--2");
//        t1.start();
//        t2.start();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    task.print1();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    task.print2();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}

class Task {
    int n;
    int num = 1;
    Semaphore s1 = new Semaphore(1);
    Semaphore s2 = new Semaphore(0);

    Task(int n) {
        this.n = n;
    }

    public void print1() throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            s1.acquire();
            System.out.println(i + Thread.currentThread().getName());
            s2.release();
        }
    }

    public void print2() throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            s2.acquire();
            System.out.println(i + Thread.currentThread().getName());
            s1.release();
        }
    }
}
